package com.ntschy.taizhou.threaddemo;

import java.util.concurrent.*;

//
public class FutureTest {


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        UserInfoService userInfoService = new UserInfoService();
        MedalService medalService = new MedalService();
        long userId =666L;
        long startTime = System.currentTimeMillis();

        //调用用户服务获取用户基本信息
        // 两个future任务是并行的.
        FutureTask<UserInfo> userInfoFutureTask = new FutureTask<>(new Callable<UserInfo>() {
            @Override
            public UserInfo call() throws Exception {
                return userInfoService.getUserInfo(userId);
            }
        });
        System.out.println("---1-");
        // 对submit的任务, 是异步任务, 会并行执行,(并发执行, 缩短程序运行时间.)
        executorService.submit(userInfoFutureTask);
        //Thread.sleep(300); //模拟主线程其它操作耗时
        FutureTask<MedalInfo> medalInfoFutureTask = new FutureTask<>(new Callable<MedalInfo>() {
            @Override
            public MedalInfo call() throws Exception {
                return medalService.getMedalInfo(userId);
            }
        });
        executorService.submit(medalInfoFutureTask);
        System.out.println("---2-");


        //  如果没有get返回值,主线程会很快执行完毕, ; 如果有get, 会阻塞主线程来获取结果.
        //  此时,在get结果时, 线程又是串行的,会阻塞主线程. 没啥问题, 符合程序运行逻辑.
        UserInfo userInfo = userInfoFutureTask.get();//获取个人信息结果
        System.out.println("---3-");
        MedalInfo medalInfo = medalInfoFutureTask.get();//获取勋章信息结果
        System.out.println("---4-");

        executorService.shutdown();
        System.out.println("总共用时" + (System.currentTimeMillis() - startTime) + "ms");
    }


}
